import datetime

from flask import Blueprint, render_template

from apps.util import mysql_do
from ext import socketio

test_bp = Blueprint('test', __name__, url_prefix='/test')

# 通信命名空间
name_space = '/dcenter'
# 公共变量
class_name = ''
should_num = ''
sick_num = ''
leader_name = ''
people_num = ''
status = ''
weather = ''


@test_bp.route('/')
def index():
    now_time = datetime.datetime.now().strftime('%Y-%m-%d')
    return render_template('pageA.html', now_time=now_time)


@test_bp.route('/class_insert')
def class_insert(class_name='测试集训名称1', should_num='10', sick_num='2', leader_name='张首长',
                 status="近日，近日的近日是今日，测试测试测试测试测试测试测试测试测试测试测试测试!", weather="微风,天气：晴"):
    class_id = mysql_do.Class_insert(class_name, should_num, sick_num, leader_name, status, weather)
    if class_id != 0:
        return 'class_id:' + str(class_id)
    else:
        return 't_class插入失败'


@test_bp.route('/people_insert')
def people_insert(name='李四', job='连长', unit='北方某连队', group='第三小组', pic_url='qwewqewqewqewqewqewqewqeqqweqe'):
    global class_name, should_num, sick_num, leader_name, people_num, status, weather
    event_name = 'dcenter'
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    people_id = mysql_do.People_insert(name, job, unit, group, now_time, pic_url)
    if people_id != 0:
        t_class = mysql_do.Select_class()
        for class_line in t_class:
            class_name = class_line[1]
            should_num = str(class_line[2])
            sick_num = str(class_line[3])
            leader_name = class_line[4]
            status = class_line[5]
            weather = class_line[6]
        relationship_id = mysql_do.Relationship_insert(999, people_id)
        count_num = mysql_do.Count_num()
        for count_line in count_num:
            people_num = str(count_line)
        lose_num = int(should_num) - int(sick_num) - int(people_num)

        data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                'sick_num': sick_num, 'lose_num': lose_num, 'people_num': people_num, 'leader_name': leader_name,
                'status1': status, 'weather': weather
                }
        if lose_num <= 0:
            data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                    'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                    'sick_num': sick_num, 'lose_num': '0', 'people_num': people_num, 'leader_name': leader_name,
                    'status1': status, 'weather': weather
                    }
        print(data)
        socketio.emit(event_name, data, broadcast=False, namespace=name_space)
        return 'people_id:' + str(people_id) + ',relationship_id:' + str(relationship_id)
    else:
        return 't_people插入失败'
